import asyncio
import datetime
import logging
import os

from mirai import FriendMessage, GroupMessage, TempMessage
from mirai.models.api import Recall
from mirai.models.events import MessageEvent, GroupRecallEvent

from robot_core.robot_factory import RobotFactory
from robot_service.service_dispatcher import ServiceDispatcher

logging.basicConfig(level=logging.WARNING,
                    format="%(asctime)s %(name)s %(levelname)s %(message)s",
                    datefmt='%Y-%m-%d  %H:%M:%S %a',
                    filename='./robot_log/pip_boy.log')

# 哔哔小子实例
pip_boy = RobotFactory().get_robot('pip_boy')
dispatcher = ServiceDispatcher(pip_boy)
app = pip_boy.asgi


# 好友
@pip_boy.on(FriendMessage)
async def on_friend_message(event: FriendMessage):
    await dispatcher_run(event)


# 群消息
@pip_boy.on(GroupMessage)
async def on_group_message(event: GroupMessage):
    await dispatcher_run(event)


# 临时会话
@pip_boy.on(TempMessage)
async def on_temp_message(event: TempMessage):
    await dispatcher_run(event)


# TODO 完成这个撤回功能
@pip_boy.on(GroupRecallEvent)
async def recall_message(event: GroupRecallEvent):
    print("recall")
    pass


async def dispatcher_run(event: MessageEvent):
    await dispatcher.service_dispatcher(event)


@pip_boy.add_background_task()
async def timer():
    today_finished = False
    while True:
        await asyncio.sleep(1)
        now = datetime.datetime.now()
        if now.hour == 8:
            if not today_finished:
                await dispatcher.message_push()
                os.system("cd sir_two_spider && scrapy crawl dino")
                os.system("cd sir_two_spider && scrapy crawl lindexi")
                os.system("cd sir_two_spider && scrapy crawl lvyi")
                today_finished = True
        if now.hour > 8:
            today_finished = False


try:
    pip_boy.run(port=8099)
    # pip_boy.run(port=8091)
except Exception as e:
    logging.exception(e)
